package com.my.app.code;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.core.annotation.AnnotationUtils;

import com.my.annotation.Model;
import com.my.toolkit.IOUtil;
import com.my.toolkit.template.TemplateUtil;
import com.my.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CodeCreator {

	private TemplateUtil templateUtil;
	CodeCreatorProperties properties;
	private String output;

	public CodeCreator(TemplateUtil templateUtil, CodeCreatorProperties properties) {
		this.templateUtil = templateUtil;
		this.properties = properties;
		output = properties.getOutPutDir();
		if (StringUtil.isNotEmpty(output)) {
			try {
				Files.createDirectories(Paths.get(output));
			} catch (IOException e) {
				log.warn("创建目录失败:"+output,e);
				output = null;
			}
		}
	}

	public String getMapperXml(Class daoClass) throws Exception {
		Type[] ptClass = daoClass.getGenericInterfaces();
		if (ptClass.length != 1) {
			return null;
		}
		ParameterizedType type = (ParameterizedType) ptClass[0];
		Type t = type.getActualTypeArguments()[0];
		Class model = (Class) t;

		Map map = toRootMap(daoClass, model);

		log.info("准备生成mapper.xml:" + daoClass.getName() + "<" + model.getName() + ">");
		Model modelAnn = AnnotationUtils.findAnnotation(model, Model.class);
		if (modelAnn == null) {
			log.info("未设置Model标签,跳过:" + model);
			return null;
		}
		String xml = templateUtil.parseTemplate(properties.getMapperXml(), map);
		if (output!=null) {
			String name =output + "/" + model.getSimpleName() + "Mapper.xml";
			IOUtil.createFile(name, xml);
			log.info("生成文件:" + name);
		} else {
			log.debug("生成映射文件\n{}", xml);
		}

		return xml;
	}


	private Map toRootMap(Class daoClass, Class modelClass) {
		Map map = new HashMap();
		map.put("daoClass", daoClass.getName());
		map.put("modelClass", modelClass.getName());
		map.put("help", new CodeCreatorHelper(modelClass));
		return map;
	}

	public String getBasePackage() {
		return properties.getBasePackage();
	}
}
